import React, {PureComponent, useRef} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  PermissionsAndroid,
  DeviceEventEmitter,
  Platform,
  Alert,
  Button,
  // Share,
} from 'react-native';
import I18n from 'react-native-i18n';
import Share from 'react-native-share';
import Clipboard from '@react-native-community/clipboard';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import LayoutConstants from '../../config/LayoutConstants';
import {
  ImageButton,
  LinearBoardButton,
  LinearButton,
  TextButton,
} from '../../components/Button';
import ViewShot from 'react-native-view-shot';
import CameraRoll from '@react-native-community/cameraroll';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {LinerBoardTextInput} from '../../components/TextInput';
import {NormalHeader} from '../../components/NavigationHeader';
import {
  follow,
  query,
  updateUser,
  getClubInfo,
  registClub,
} from '../../api/user';
import {showToast} from '../../components/Toast';
import {updateUserInfo} from '../../redux/action';
import {BASE_API} from '../../config';
import LinearGradient from 'react-native-linear-gradient';
import {ScrollView} from 'react-native-gesture-handler';
import ModalHandler from '../../components/ModalHandler';
import QRCode from 'react-native-qrcode-svg';

class InviteFriendScreen extends BaseComponent {
  constructor(props) {
    super(props);
    // this.photoViewRef = React.createRef()
    this.state = {
      user: props.userInfo,
    };
  }

  componentDidMount() {
    this._queryUserInfo();
  }

  getPermissionAndroid = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: 'Image Download Permission',
          message: 'Your permission is required to save images to your device',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        return true;
      }
      Alert.alert(
        '',
        'Your permission is required to save images to your device',
        [{text: 'OK', onPress: () => {}}],
        {cancelable: false},
      );
    } catch (err) {
      // handle error as you please
      console.log('err', err);
    }
  };

  _queryUserInfo = () => {
    query({
      userToken: this.props.userInfo.token,
    }).then((resp) => {
      let user = resp.data;
      this.setState({
        user: user,
      });
    });
  };

  savePhoto = () => {
    this.refs.photoViewRef.capture().then((uri) => {
      const image = CameraRoll.save(uri, 'photo');
      if (image) {
        showToast('Image saved successfully');
      }
    });
  };

  shareInvite = async () => {
    // const result = await Share.share({
    //   title: 'Everything signin',
    //   message: 'Please install this app and stay safe , AppLink :https://play.google.com/store/apps/details?id=nic.goi.aarogyasetu&hl=en',
    //   url: 'https://play.google.com/store/apps/details?id=nic.goi.aarogyasetu&hl=en'
    // });

    this.refs.photoViewRef.capture().then((uri) => {
      const shareOptions = {
        title: 'Everything signin',
        url: uri,
        failOnCancel: false,
      };
      Share.open(shareOptions)
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          err && console.log(err);
        });
    });
  };

  renderComponent = () => {
    let avatar =
      this.state.user.image.indexOf('http') == -1
        ? BASE_API + this.state.user.image
        : this.state.user.image;

    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Invite Friends"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <ScrollView>
          <View
            style={{
              alignItems: 'center',
            }}>
            <ViewShot
              style={{
                marginTop: 20,
                position: 'relative',
              }}
              ref="photoViewRef"
              options={{format: 'png', quality: 0.9}}>
              <Image
                style={{
                  width: 334,
                  height: 594,
                }}
                source={require('../../assets/user/invite_bg.png')}></Image>
              <View
                style={{
                  position: 'absolute',
                  top: 145,
                  left: 0,
                  right: 0,
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                <View
                  style={{
                    padding: 10,
                    backgroundColor: '#fff',
                    borderRadius: 16,
                  }}>
                  <QRCode
                    size={LayoutConstants.WINDOW_WIDTH - 240}
                    backgroundColor="#A1A1A1"
                    color="white"
                    logo={{uri: avatar}}
                    value={
                      BASE_API +
                      '/app.html?inviteCode=' +
                      this.state.user.inviteCode
                    }
                  />
                </View>
              </View>
            </ViewShot>

            <View
              style={{
                marginTop: 30,
                alignItems: 'center',
              }}>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                <Text
                  style={{
                    color: '#fff',
                    fontSize: 18,
                  }}>
                  Code: {this.state.user.inviteCode}
                </Text>
                <TouchableOpacity
                  style={{
                    backgroundColor: '#47375c',
                    paddingHorizontal: 10,
                    paddingVertical: 4,
                    borderRadius: 20,
                    marginLeft: 10,
                  }}
                  onPress={() => {
                    Clipboard.setString(this.state.user.inviteCode);
                    showToast('Copied!', undefined, 3000);
                  }}>
                  <Text
                    style={{
                      color: '#fff',
                    }}>
                    Copy
                  </Text>
                </TouchableOpacity>
              </View>

              <View
                style={{
                  marginTop: 10,
                  flexDirection: 'row',
                }}>
                <LinearButton
                  text="Save to photo"
                  buttonStyle={{
                    backgroundColor: '#FFCB26',
                    width: 150,
                  }}
                  onPress={() => {
                    this.savePhoto();
                  }}
                />

                <LinearButton
                  text="Send invites"
                  buttonStyle={{
                    backgroundColor: '#FFCB26',
                    marginLeft: 20,
                    width: 150,
                  }}
                  onPress={() => {
                    this.shareInvite();
                  }}
                />
              </View>
            </View>
          </View>
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </ScrollView>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  manager: state.Chain.manager,
  navigationStack: state.Layout.navigationStack,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
});

export default connect(mapStateToProps, mapDispatchToProps)(InviteFriendScreen);
